/** @format */

import Vue from "vue"
import VueRouter from "vue-router"
import routes from "./ALL_ROUTES"
import permission from "_libs/permission"
import store from "_store"
import config from "@/config"

/**
 * 模拟后台登录返回的权限
 *
 * 1. 一个人可以拥有多个权限，但是后端要对多个角色的用户 key 做去重处理
 * 2. 单独判断是 superAdmin superAdmin 权限放开
 * 3. permissions 字段 示例 home.user.add
 * home 代表主页
 * user 代表用户设置
 * add 代表添加操作
 * */

Vue.use(VueRouter)

const router = new VueRouter({
    routes: routes
})

const LOGIN_PAGE_NAME = "login"
const WHITE_NAME = ["error_404_page", "error_404", "error_500", "error_401"]

const localData = window.localStorage.getItem("__USER_KEY__")
const {token, session_key} = localData && JSON.parse(localData) || {}

router.beforeEach((to, from, next) => {
    // const userData = store.state.auth.userData || {}
    let hasUserInfo = token && session_key

    if (!hasUserInfo && to.name === LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next()
    } else if (hasUserInfo && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        next({
            name: to.query.back_url || config.homeRouterName, // 跳转到homeName页
            replace: true
        })
    } else if (!hasUserInfo && to.name !== LOGIN_PAGE_NAME && !WHITE_NAME.some(item => item === to.name)) {
        // 未登录且要跳转的页面不是登录页 , 并且非白名单页面
        next({
            name: LOGIN_PAGE_NAME, // 跳转到登录页
            query: {
                back_url: to.name
            },
            replace: true
        })
    } else {
        if (token && session_key) {
            next()
        } else {
            next({
                name: LOGIN_PAGE_NAME, // 跳转到登录页
                replace: true
            })
        }
    }
})

const setTitle = (toRouter = {}) => {
    const {title = "", showTitle = true} = toRouter.meta
    let defaultTitle = config.productName
    if (showTitle) {
        document.title = defaultTitle + " - " + title
        return
    }
    document.title = defaultTitle
}
router.afterEach(to => {
    // console.log("afterEach", to);
    setTitle(to)
    window.scrollTo(0, 0)
})

export default router
